package middleware

import (
	"gin-chat/pkg"
	"gin-chat/router/response"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"net/http"
)

const (
	SessionKey = "sessionId"
	KEY        = "chat10086"
)

// 使用 Cookie 保存 session
func EnableCookieSession() gin.HandlerFunc {
	store := cookie.NewStore([]byte(KEY))
	options := sessions.Options{
		Path:     "/",
		MaxAge:   86400 * 30,
		SameSite: 0,
	}
	store.Options(options)
	return sessions.Sessions("SAMPLE", store)
}

func AuthSessionMiddle() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			app          = response.Gin{C: c}
			session      = sessions.Default(c)
			sessionValue = session.Get(SessionKey)
		)
		if sessionValue == nil {
			app.Response(http.StatusInternalServerError, pkg.NotLogin, sessionValue)
			return
		}
		c.Set("uuid", sessionValue)
		c.Next()
		return
	}
}
